<?php
namespace app\common\model;

use \app\common\model\Auth;
use \app\common\model\AuthRecord;
use \think\Model as ThinkphpModel;
use \think\Request;
use \think\Session;
use \think\Validate;

class User extends ThinkphpModel
{
    public function getUserByName($user_name)
    {
        return $this->getUserBy('user_name', $user_name);
    }
    public function getUserById($id)
    {
        return $this->getUserBy('user_id', $id);
    }
    public function getUserByUserId($id)
    {
        $map['user_id'] = $id;
        return $this->where($map)->find();
    }
    public function getUserBy($filed, $value)
    {
        $map[$filed] = $value;
        $user_info   = $this->where($map)->find();
        if ($user_info) {
            return $user_info->toArray();
        } else {
            return false;
        }
    }
    public function getPost()
    {
        if (IS_POST) {
            $data['user_name'] = input('post.user_name');
            $data['user_pwd']  = input('post.user_pwd');
            return $data;
        } else {
            return false;
        }
    }

    public function checkForm($data, $scene = '')
    {
        $validate = validate('User');
        $res      = $validate->scene($scene)->check($data);
        if (!$res) {
            return $validate->getError();
        } else {
            return false;
        }
    }

    public function updateLoginInfo($user_name)
    {
        $map['user_name']        = $user_name;
        $data['last_login_time'] = date('Y-m-d H:i:s', time());
        $data['last_login_ip']   = inge_get_ip();
        $this->where($map)->update($data);
    }

    public function checkUserStatus($id)
    {
        $user_info = $this->getUserById($id);
        if ($user_info['status'] == 0) {
            $mess['code'] = '-1';
            $mess['info'] = '当前用户被禁用';
            return json($mess);
        } elseif ($user_info['is_del'] == 1) {
            $mess['code'] = '-1';
            $mess['info'] = '当前用户不存在';
            return json($mess);
        }
    }

    /***
     * 关联对象
     */
    public function getAuth()
    {
        if ($this->auth_id == 0) {
            return null;
        }
        $auth = Auth::where('auth_id', $this->auth_id)->find();
        return $auth;
    }

    /**
     * @name 获取权限中的记录
     */
    public function getAuthRecordOneByRulValue($rule_value, $data)
    {
        $map['rule_value'] = $rule_value;
        $map['data']       = $data;
        $authRecord        = AuthRecord::where('auth_id', $this->auth_id)->where($map)->find();
        return $authRecord;
    }
    /**
     * 保存用户
     * 传入ID和post数据
     * $allowfield 如果只需要更新或添加几项列，则限制此参数
     */
    public function saveUserInfo($post, $id = '', $allowField = true)
    {
        $msg           = array();
        
        $post['sex']   = isset($post['sex']) ? $post['sex'] : 0;
        if ($id && $post['user_pwd'] == '') {
            $post['user_pwd'] = 'PWDISNULL';
            $pwd              = 1;
        } else {
            $pwd = 0;
        }
        $res = $this->checkForm($post);
        if ($pwd == 1) {
            $post['user_pwd'] = '';
        }
        if ($res) {
            $msg['code'] = '0';
            $msg['msg']  = $res;
            return $msg;
        }
        
        $data['sex']   = isset($post['sex']) ? $post['sex'] : 0;
        $map           = array();
        if ($id) {
            $map['user_id'] = ['<>', $id];
        }else{
            /**
             * 新增用户才可以设置初始金币和积分。
             */
            $post['coin']  = str_replace(",", "", $post['coin']);
            $post['score'] = str_replace(",", "", $post['score']);
            $data['coin']  = $post['coin'] == false ? '0.00' : $post['coin'];
            $data['score'] = $post['score'] == false ? '0' : $post['score'];
        }
        $map['user_name'] = $post['user_name'];
        $map['is_del'] = 0;
        $res = $this->where($map)->find();
        // var_dump($res);die();
        if (!$res) {
            $data['user_name'] = $post['user_name'];
            unset($map['user_name']);
        } else {
            $msg['code'] = '0';
            $msg['msg']  = '用户名重复';
            return $msg;
        }
        if (isset($post['user_nicename']) && $post['user_nicename']!='') {
            $map['user_nicename'] = $post['user_nicename'];
            if (!$this->where($map)->find()) {
                $data['user_nicename'] = $post['user_nicename'];
                unset($map['user_nicename']);
            } else {
                $msg['code'] = '0';
                $msg['msg']  = '昵称重复';
                return $msg;
            }
        }elseif ($post['user_nicename']=='') {
            $post['user_nicename'] = NULL;
        }
        if ($post['user_pwd']) {
            $data['user_pwd_rand'] = inge_get_random_str('10');
            $data['user_pwd']      = inge_encryption_pwd($post['user_pwd'], $data['user_pwd_rand']);
        }
        if (isset($post['email']) && $post['email'] != '') {
            $map['email'] = $post['email'];
            if (!$this->where($map)->find()) {
                $data['email'] = $post['email'];
                unset($map['email']);
            } else {
                $msg['code'] = '0';
                $msg['msg']  = '邮箱重复';
                return $msg;
            }
        }
        if (isset($post['mobile']) && $post['mobile'] != '') {
            $map['mobile'] = $post['mobile'];
            // var_dump($this->where($map)->find());
            if (!$this->where($map)->find()) {
                $data['mobile'] = $post['mobile'];
                unset($map['mobile']);
            } else {
                $msg['code'] = '0';
                $msg['msg']  = '手机号重复';
                return $msg;
            }
        }
        $data['user_url']         = isset($post['user_url']) ? $post['user_url'] : '';
        $data['signature']        = isset($post['signature']) ? $post['signature'] : '';
        $data['status']           = isset($post['status']) ? 1 : 0;
        $data['email_confirmed']  = isset($post['email_confirmed']) ? 1 : 0;
        $data['mobile_confirmed'] = isset($post['mobile_confirmed']) ? 1 : 0;
        // var_dump($data);
        if ($id) {
            $map['user_id'] = $id;
            //判断是否参数未改直接提交更新
            $res = $this->allowField($allowField)->where($map)->where($data)->find();
            if (!$res) {
                $res = $this->allowField($allowField)->where($map)->update($data);
            }
            if ($res) {
                $msg['code'] = '1';
                $msg['msg']  = '更新成功';
                return $msg;
            } else {
                $msg['code'] = '0';
                $msg['msg']  = '更新失败';
                return $msg;
            }
        } else {
            $data['user_type'] = 1;
            $res               = $this->allowField($allowField)->insertGetId($data);
            if ($res) {
                $msg['code'] = '1';
                $msg['msg']  = $res;
                return $msg;
            } else {
                $msg['code'] = '0';
                $msg['msg']  = $res;
                return $msg;
            }
        }
    }
    /**
     * 根据字段获取用户
     * @param  [type] $field [任意字段数值]
     * @param  [type] $repeat [需要排除的ID]
     * @return [type]           [description]
     */
    public function getUserByField($field,$value,$repeat='')
    {
        if($repeat != ''){
            $res = $this->where('user_id','<>',$repeat)->where($field,$value)->find();
        }else{
            $res = $this->where($field,$value)->find();
        }
        return $res;
    }

}
